//
//  HJMyAccessController.m
//  Keping
//
//  Created by a on 2017/8/28.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HJMyAccessController.h"
#import "HJUnlockCardController.h"

#import "HJSelectCardView.h"
#import "HJSelectDateView.h"
#import "HJSuperstarSoccerCell.h"

#import "HJEntranceCardsListRequest.h"
#import "KLockAccessCardRequest.h"

#import "KEntranceCardsListModel.h"
#import "HJCellModel.h"

@interface HJMyAccessController ()<UITableViewDelegate,UITableViewDataSource,HJSelectCardViewDelegate,HJSelectDateViewDelegate>
/**
 tableView
 */
@property(nonatomic,weak)UITableView*tableView;
/**
 数据源
 */
@property(nonatomic,strong)NSMutableArray *dataAry;
/**
 门禁卡数据
 */
@property(nonatomic,strong)KEntranceCardsListModel*entranceCardsListModel;
/**
 锁参数
 */
@property(nonatomic,assign)BOOL UntilUnlock;
@end

@implementation HJMyAccessController
-(NSMutableArray *)dataAry
{
    if (!_dataAry) {
        HJCellModel*cell1=[HJCellModel cellModelTitle:@"Card" content:@""];
        HJCellModel*cell2=[HJCellModel cellModelTitle:@"Start" content:@""];
        HJCellModel*cell3=[HJCellModel cellModelTitle:@"Until Unlock" content:@""];
        HJCellModel*cell4=[HJCellModel cellModelTitle:@"Date & Time" content:@""];
        _dataAry = [[NSMutableArray alloc] initWithObjects:[@[cell1,cell2] mutableCopy],[@[cell3,cell4] mutableCopy], nil];
    }
    return _dataAry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

-(void)setUI
{
    self.navigationItem.title=@"My Access Cards";
    
    CGFloat H=K_FactorH(45);
    UITableView*tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-H) style:UITableViewStyleGrouped];
    tableView.delegate=self;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    self.tableView=tableView;
    
    //添加table尾部
    UIView*footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, K_FactorH(80))];
    tableView.tableFooterView=footerView;
    footerView.backgroundColor=[UIColor clearColor];
    CGFloat margin =K_FactorW(20);
    UIButton*addBtn=[[UIButton alloc]initWithFrame:CGRectMake(margin, K_FactorH(30), footerView.width-2*margin, footerView.height-K_FactorH(30))];
    [footerView addSubview:addBtn];
    addBtn.layer.cornerRadius=addBtn.height/2;
    addBtn.layer.masksToBounds=YES;
    [addBtn setBackgroundColor:[UIColor colorWithHexString:@"#6853fa"] forState:UIControlStateNormal];
    [addBtn setTitle:@"Lock Access Card" forState:UIControlStateNormal];
    addBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [addBtn addTarget:self action:@selector(clickLockAccess) forControlEvents:UIControlEventTouchUpInside];
    
    //unlock a Card
    UIButton*unlockBtn=[[UIButton alloc]initWithFrame:CGRectMake(0,self.view.height-H, self.view.width,H)];
    [self.view addSubview:unlockBtn];
    [unlockBtn setBackgroundColor:[UIColor colorWithHexString:@"#6853fa"] forState:UIControlStateNormal];
    [unlockBtn setTitle:@"Unlock a Card >>" forState:UIControlStateNormal];
    unlockBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [unlockBtn addTarget:self action:@selector(clickUnlockBtn) forControlEvents:UIControlEventTouchUpInside];

    

}
-(void)getData
{
    [super getData];
    [self showLoading];

    HJEntranceCardsListRequest* listRequest = [HJEntranceCardsListRequest new];
    WEAKSELF;
    [listRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        weakSelf.entranceCardsListModel = [KEntranceCardsListModel modelWithJSON:request.responseData];
        if (weakSelf.entranceCardsListModel.statusCode == 200) {
            [weakSelf.tableView reloadData];
        }else{
            [weakSelf showErrorText:weakSelf.entranceCardsListModel.msg errCode:weakSelf.entranceCardsListModel.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

#pragma mark 开锁与解锁
-(void)clickLockAccess
{
    HJCellModel*cellModel=self.dataAry[0][0];
    if (!cellModel.content.length) {
        ALERT(@"please select Card");
        return;
    }
    KLockAccessCardRequest* lockRequest = [[KLockAccessCardRequest alloc]initWithCarId:cellModel.cardID];
    lockRequest.params=[NSDictionary dictionaryWithObjectsAndKeys:[self.dataAry[0][1] content],@"startTime",self.UntilUnlock?@"":[self.dataAry[1][1] content],@"endTime",@"N",@"status",nil];
    WEAKSELF;
    [lockRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        //type1
        KEntranceCardsListModel *model = [KEntranceCardsListModel modelWithJSON:request.responseData];
        if (model.statusCode == 200) {
            [weakSelf showSuccess: model.msg];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            [weakSelf showErrorText:model.msg errCode:model.statusCode];
        }
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

#pragma mark 解锁门禁卡
-(void)clickUnlockBtn
{
    HJUnlockCardController *vc = [HJUnlockCardController new];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataAry[section] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    HJSuperstarSoccerCell*cell=[HJSuperstarSoccerCell cellWithTableView:tableView];
    cell.isShowArrow=NO;
    if (indexPath.section==1&&indexPath.row==0) {
        CGFloat btnWH=K_FactorW(30);
        UIButton*btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0,btnWH,btnWH)];
        [btn setImage:[UIImage imageNamed:@"card_unlock"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"card_lock"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(clickSelect:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView=btn;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    } else {
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.cellModel=self.dataAry[indexPath.section][indexPath.row];
    return cell;
}
-(void)clickSelect:(UIButton*)btn
{
    btn.selected=!btn.selected;
    self.UntilUnlock=btn.selected;
    if (self.UntilUnlock) {
        HJCellModel *model = self.dataAry[1][1];
        model.content = @"∞";
        [self.dataAry[1] replaceObjectAtIndex:1 withObject:model];
        [self.tableView reloadRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1] withRowAnimation:UITableViewRowAnimationNone];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
    switch (indexPath.row) {
        case 0:
        {
            HJSelectCardView *cardView=[[HJSelectCardView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height)];
            cardView.delegate=self;
            cardView.dataAry = self.entranceCardsListModel.entranceCardViews;
            [self.navigationController.view addSubview:cardView];
        }
            break;
        case 1:
        {
             [self creatDatePicker:UIDatePickerModeDate indexPath:indexPath];
        }
            break;
        default:
            break;
        }
    }else if (indexPath.section==1)
    {
        switch (indexPath.row) {
            case 0:
            {
            }
                break;
            case 1:
            {
                if (!self.UntilUnlock) {
                    [self creatDatePicker:UIDatePickerModeDate indexPath:indexPath];
                }
            }
                break;
            default:
                break;
        }
    }
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return @"lock a Card";
    }else
    {
        return @"End";
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(35);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(55);
}
#pragma mark  -- HJSelectCardViewDelegate
-(void)selectCardView:(HJSelectCardView *)selectCardView clickSelectCard:(KEntranceCardViewsModel *)entranceCardViews{
    //填充门卡
    HJCellModel*cellModel=self.dataAry[0][0];
    cellModel.content=entranceCardViews.cardNo;
    cellModel.cardID = entranceCardViews.id;
    [self.tableView reloadRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    
}
#pragma mark -- HJSelectDateViewDelegate
-(void)selectDateView:(HJSelectDateView *)selectDateView clickSelectDate:(NSString *)dateStr indexPath:(NSIndexPath *)indexPath
{
    HJCellModel *cellModel=self.dataAry[indexPath.section][indexPath.row];
    if (selectDateView.DateModel == UIDatePickerModeDate) {
        cellModel.content = dateStr;
        [self creatDatePicker:UIDatePickerModeTime indexPath:indexPath];
    } else {
        cellModel.content = [[cellModel.content stringByAppendingString:@" "] stringByAppendingString:[NSString stringWithFormat:@"%@:00",dateStr]];
    }
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(void)creatDatePicker:(UIDatePickerMode)dateModel indexPath:(NSIndexPath*)indexPath
{
    HJSelectDateView*dateView=[[HJSelectDateView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height)];
    dateView.delegate=self;
    dateView.DateModel=dateModel;
    dateView.indexPath=indexPath;
    [self.navigationController.view addSubview:dateView];
}
@end
